package com.yxplearn.mybatisplus.controller;

import com.yxplearn.mybatisplus.pojo.UserRecord;
import com.yxplearn.mybatisplus.service.UserRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/buy")
public class MiaoShaController {

    private static final String ITEM_KEY = "itemkey";
    private static final int MAX_NUM = 100;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserRecordService userRecordService;

    @RequestMapping("/buyOneItem")
    public HttpResponseMsg buyOneItem() {
        Long increment = redisTemplate.opsForValue().increment(ITEM_KEY, 1);
        if (increment <= MAX_NUM) {
            UserRecord userRecord = new UserRecord();
            userRecord.setId(increment);
            userRecord.setPlayerName("yxp" + increment);
            userRecord.setMapValue(Collections.EMPTY_MAP);
            userRecord.setListValue(Collections.EMPTY_LIST);
            userRecordService.saveOne(userRecord);
            return new HttpResponseMsg(1, "success");
        }
        return new HttpResponseMsg(0, "fail");
    }

    @RequestMapping("/insertRedisKey")
    public HttpResponseMsg insertRedisKey() {
        redisTemplate.opsForValue().set(ITEM_KEY, 1);
        redisTemplate.expire(ITEM_KEY, 1, TimeUnit.SECONDS);
        return new HttpResponseMsg(1, "success");
    }
}
